package com.samoiloff.ui.list.smart.model {
	import com.samoiloff.owncrosswords.viewers.classic.Settings;
	import com.samoiloff.ui.list.smart.interfaces.CellRenderer;
	import com.slavshik.utils.Fonts;

	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.geom.Rectangle;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;

	/**
	 * @author Samoiloff
	 */
	public class SmartListCellRenderer extends CellRenderer {
		
		private static const OVER_BG_COLOR		: int = 0xf0ece2;
		private static const SELECTED_BG_COLOR	: int = 0xc5ead8;
		private static const NORMAL_BG_COLOR	: int = 0xffffff;
		
		private static const SPACE:int = 2;
		
		protected var _bgMc		: Sprite;
				
		protected var _tf		: TextField;

		public function SmartListCellRenderer(data:* = null, index:int = 0) {
			super(data, index);
		}

		override public function instantiate(data: *, index: int): CellRenderer {
			return new SmartListCellRenderer(data, index);
		}
		
		override public function calculateBounds(bounds : Rectangle) : Rectangle {
			_tf.autoSize = TextFieldAutoSize.NONE;
			_tf.height = 10;
			_tf.width = bounds.width;
			_tf.autoSize = TextFieldAutoSize.LEFT;
			return new Rectangle(bounds.x, bounds.y, bounds.width, _tf.height + 2*SPACE);
		}
		
		override protected function render(): void {
			super.render();
			
			_bgMc = new Sprite();
			_mc.addChild(_bgMc);
			
			_tf = Fonts.getInstance().getDefaultTf(_data.label);
			Fonts.getInstance().applyTfTextFormat(_tf, Settings.getInstance().enabledFormat);
			_tf.wordWrap = true;
			
			_mc.addChild(_tf);
			//_tf.border = true;

			if (_bounds) {
				_tf.width = _bounds.width;
			}
			
			_tf.y = SPACE;
			
			_mc.addEventListener(MouseEvent.MOUSE_OUT, onMouseOut);
			_mc.addEventListener(MouseEvent.MOUSE_OVER, onMouseOver);
			
			updateBgMc(false);
		}

		override protected function obscure(): void {
			_mc.removeEventListener(MouseEvent.MOUSE_OUT, onMouseOut);
			_mc.removeEventListener(MouseEvent.MOUSE_OVER, onMouseOver);
			
			_tf = null;
			_bgMc = null;
			
			super.obscure();
		}
		
		private function onMouseOut(event: MouseEvent): void {
			updateBgMc();
		}

		private function onMouseOver(event: MouseEvent): void {
			updateBgMc(true);
		}
		
		
		override public function set selected(selected: Boolean): void {
			super.selected = selected;
			updateBgMc();
		}
		
		protected function updateBgMc(over:Boolean = false):void {
			if (visible) {
				_bgMc.graphics.clear();
				if (selected) {
					_bgMc.graphics.beginFill(SELECTED_BG_COLOR);
				} else {
					if (over) {
						_bgMc.graphics.beginFill(OVER_BG_COLOR);
					} else {
						_bgMc.graphics.beginFill(NORMAL_BG_COLOR);
					}
				}
				if (_bounds) {
					_bgMc.graphics.drawRect(0, 0, bounds.width, bounds.height);
				}
			}
		}
		
	}
}
